package View.JTable;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import Error.Errormanager;
import View.MainUI;
import View.CoolSwing.MyMenuItem;
import View.CoolSwing.MyTextField;
import View.JFrame.JRenameFrame;
import View.JPanel.JArrorwPanel;
import View.JPanel.JInformationPanel;

public class JAnimationTable extends JTable implements MouseListener {
	/**
	 * serialVersionUID;
	 */
	private static final long serialVersionUID = -8769742094982924954L;
	private File directory = FileSystemView.getFileSystemView().getHomeDirectory();
	private int index;
	private JInformationPanel jInfo;
	private JArrorwPanel jArrorw;
	private List<File> history = new ArrayList<File> ();
	private int now = -1;
	private JPopupMenu jPopupMenu = new MyPopupMenu();
	private Desktop desktop;
	private DefaultCellEditor cellEditor;
	private boolean editable = false;
	private	Errormanager error = new Errormanager(); 
	
	/**
	 * SetDirectionary
	 * @param directionary
	 */
	public void setDirectionary(File directionary) {
		this.directory = directionary;
		JAnimationTableModel model = (JAnimationTableModel) getModel();
		model.setFileDirectory(directionary, index);
		jArrorw.setAddress(directionary.getPath());
		repaint();
		revalidate();
	}

	/**
	 * get the Directory;
	 * @return directory
	 */
	public File getDirectory() {
		return directory;
	}

	/**
	 * Constructor
	 * @param index The index of RuleList;
	 */
	public JAnimationTable(int index) {
		this.index = index;
		setModel(new JAnimationTableModel(directory, index));
	    TableColumnModel tcm = getColumnModel();
	    TableColumn tc1 = tcm.getColumn(0);
	    tc1.setPreferredWidth(tc1.getMinWidth());
	    TableColumn tc2 = tcm.getColumn(1);
	    tc2.setPreferredWidth(300);
	    TableColumn tc3 = tcm.getColumn(2);
	    tc3.setPreferredWidth(tc3.getMinWidth());
	    TableColumn tc4 = tcm.getColumn(3);
	    tc4.setCellRenderer(new MyTableCellRenderer());
	    tc4.setPreferredWidth(tc4.getMinWidth());
	    TableColumn tc5 = tcm.getColumn(4);
	    tc5.setCellRenderer(new MyTableCellRenderer());
	    tc5.setPreferredWidth(tc5.getMinWidth());
	    
	    //Desktop;
	    if (Desktop.isDesktopSupported()) {
	    	desktop = Desktop.getDesktop();
	    }
	    
	    setDefaultRenderer(Boolean.class, new MyTableCellRenderer());
	    setDefaultRenderer(File.class, new MyTableCellRenderer());
	    setDefaultRenderer(String.class, new MyTableCellRenderer());
	    
	    setRowHeight(25);
	    cellEditor = new DefaultCellEditor(new MyTextField());
//	    cellEditor.setClickCountToStart(1);
	    tc2.setCellEditor(cellEditor);
	    
	    setShowHorizontalLines(false);
//	    setAutoResizeMode(AUTO_RESIZE_NEXT_COLUMN);
	    setOpaque(false);
	    addMouseListener(this);
	}

	/**
	 * Constructor
	 * @param index The index of RuleList;
	 * @param f		The file to directory;
	 */
	public JAnimationTable(int index, File f) {
		this.directory = f;
		this.index = index;
		setModel(new JAnimationTableModel(directory, index));
	    TableColumnModel tcm = getColumnModel();
	    TableColumn tc1 = tcm.getColumn(0);
	    tc1.setPreferredWidth(tc1.getMinWidth());
	    TableColumn tc2 = tcm.getColumn(1);
	    tc2.setPreferredWidth(300);
	    TableColumn tc3 = tcm.getColumn(2);
	    tc3.setPreferredWidth(tc3.getMinWidth());
	    TableColumn tc4 = tcm.getColumn(3);
	    tc4.setCellRenderer(new MyTableCellRenderer());
	    tc4.setPreferredWidth(tc4.getMinWidth());
	    TableColumn tc5 = tcm.getColumn(4);
	    tc5.setCellRenderer(new MyTableCellRenderer());
	    tc5.setPreferredWidth(tc5.getMinWidth());
		
	    //Desktop;
	    if (Desktop.isDesktopSupported()) {
	    	desktop = Desktop.getDesktop();
	    }
	    
	    setDefaultRenderer(Boolean.class, new MyTableCellRenderer());
	    setDefaultRenderer(File.class, new MyTableCellRenderer());
	    setDefaultRenderer(String.class, new MyTableCellRenderer());
	    
	    setRowHeight(25);
	    cellEditor = new DefaultCellEditor(new MyTextField());
//	    cellEditor.setClickCountToStart(1);
	    tc2.setCellEditor(cellEditor);
	    
	    setShowGrid(false);
	    setOpaque(false);
	    setBorder(null);
	    addMouseListener(this);
	}

	/**
	 * get the history;
	 * @return List<File>
	 */
	public List<File> getHistory() {
		return history;
	}
	
	/**
	 * set the infomationPanel to file;
	 */
	@Override
	public void valueChanged(ListSelectionEvent e) {
		super.valueChanged(e);
		if(e.getValueIsAdjusting()) {
			File selectedFile = getSelectedFile();
			jInfo.setF(selectedFile);
		}
	}

	/**
	 * mouseClicked();
	 */
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 2) {
			File f = getSelectedFile();
			if (f.canExecute()) {
				if (f.isDirectory()) {
					setDirectionary(f);
					
	    			for (int i =  getNow() + 1; i < getHistory().toArray().length; i++) {
	    				getHistory().remove(getNow() + 1);
	    			}
	    			getHistory().add(f);
	    			setNow(getNow() + 1);
				}
				else if (!f.isDirectory()) {
					try {
						desktop.open(f);
					} catch (IOException e1) {
						error.setNumber(Errormanager.FileCanNotOpen);
						error.show();
					}
				}
			}
		}
	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		if (e.isPopupTrigger()) {
			jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		if (e.isPopupTrigger()) {
			jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	/**
	 * get the table's selected file;
	 * @return File
	 */
	public File getSelectedFile() {
		File selectedFile = null;
		for (int i = 0; i < 5; i++) {
			if (getValueAt(getSelectedRow(), i) instanceof File) {
				selectedFile = (File) getValueAt(getSelectedRow(), i);
				break;
			}
		}
		return selectedFile;
	}
	
	/**
	 * registe the jInfo;
	 * @param jInfo
	 */
	public void registJInfo(JInformationPanel jInfo) {
		this.jInfo = jInfo;
	}
	
	/**
	 * regist the jArrorw;
	 * @param jArrorw
	 */
	public void registJArrorw(JArrorwPanel jArrorw) {
		this.jArrorw = jArrorw;
	}

	/**
	 * get the value of Now;
	 * @return int
	 */
	public int getNow() {
		return now;
	}

	/**
	 * set the value of Now;
	 * @param now
	 */
	public void setNow(int now) {
		this.now = now;
	}
	
	/**
	 * get the Index;
	 * @return
	 */
	public int getIndex() {
		return index;
	}

	/**
	 * set the Index;
	 * @param index
	 */
	public void setIndex(int index) {
		this.index = index;
	}

	/**
	 * get the jpopupMenu;
	 * @return JPopupMenu
	 */
	public JPopupMenu getJPopupMenu() {
		return jPopupMenu;
	}

	
	/**
	 * the Construction of MyPopupMenu;
	 * @author zmm
	 *
	 */
	public class MyPopupMenu extends JPopupMenu implements ActionListener{
		/**
		 * 
		 */
		private static final long serialVersionUID = 2712847078163892055L;
	    private Color COLOR1 = new Color(153, 222, 253); //color for border
	    private JMenuItem jmiOpen;
	    private JMenuItem jmiRe;
	    private JMenu jmiNew;
	    private JMenuItem jmiNewFile;
	    private JMenuItem jmiNewDireactory;
	    private JMenuItem jmiDelete;
	 	private JRenameFrame rename;
		
		public MyPopupMenu() {
			jmiOpen = new MyMenuItem(MainUI.s.open, MainUI.s.openIcon);
			jmiOpen.addActionListener(this);
//			jmiOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
			add(jmiOpen);
			
			jmiRe = new MyMenuItem(MainUI.s.reName, MainUI.s.renameIcon);
			jmiRe.addActionListener(this);
			jmiRe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,InputEvent.CTRL_MASK));
			add(jmiRe);
			
			jmiNew = new JMenu(MainUI.s.new1);
			jmiNewFile = new MyMenuItem(MainUI.s.newFile);
			jmiNewFile.addActionListener(this);
			jmiNewDireactory = new MyMenuItem(MainUI.s.newDirectory);
			jmiNewDireactory.addActionListener(this);
			jmiNew.add(jmiNewFile);
			jmiNew.add(jmiNewDireactory);
			add(jmiNew);
			
//			jmiCopy = new MyMenuItem("Copy", MainUI.s.copyIcon);
//			add(jmiCopy);
//			
//			jmiPaste = new MyMenuItem("Paste", MainUI.s.pasteIcon);
//			add(jmiPaste);
//			
//			jmiCut = new MyMenuItem("Cut", MainUI.s.cutIcon);
//			add(jmiCut);
			
			jmiDelete = new MyMenuItem(MainUI.s.delete, MainUI.s.deleteIcon);
			jmiDelete.addActionListener(this);
			add(jmiDelete);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == jmiRe) {
//				System.out.println(index);
//				System.out.println((File) getValueAt(getSelectedRow(), 1));
//				if (editable == true) {
//					editable = false;
//				}
//				else if (editable == false) {
//					editable = true;
//				}
				if (getSelectedRow() != -1) {
					if (rename == null) {
						rename = new JRenameFrame(getIndex(), (File)getSelectedFile());
						rename.registJAnimationtable(jArrorw.getJAnime());
						rename.setVisible(true);
					}
					else {
						rename.setFile(getIndex(), (File) getSelectedFile());
						rename.setVisible(true);
					}
				}
			}
			else if (e.getSource() == jmiOpen) {
				File f = getSelectedFile();
				if (f.canExecute()) {
					if (f.isDirectory()) {
						setDirectionary(f);
						
		    			for (int i =  getNow() + 1; i < getHistory().toArray().length; i++) {
		    				getHistory().remove(getNow() + 1);
		    			}
		    			getHistory().add(f);
		    			setNow(getNow() + 1);
					}
					else if (!f.isDirectory()) {
						try {
							desktop.open(f);
						} catch (IOException e1) {
							error.setNumber(Errormanager.FileCanNotOpen);
							error.show();
						}
					}
				}
			}
			else if (e.getSource() == jmiNewDireactory) {
				String filePath = getDirectory().getPath() + File.separator + "新建文件夹";
				filePath=filePath.toString();					//中文转换
				File myFilePath=new File(filePath);
				if(!myFilePath.exists()) {
					myFilePath.mkdir();
				}
				setDirectionary(getDirectory());
			}
			else if (e.getSource() == jmiNewFile) {
				String filePath= getDirectory() + File.separator + "新建文件夹.txt";
				filePath=filePath.toString();
				File myFilePath=new File(filePath);
				if(!myFilePath.exists()) {
					try {
						myFilePath.createNewFile();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				setDirectionary(getDirectory());
			}
			else if (e.getSource() == jmiDelete) {
				if (getSelectedFile() != null) {
					getSelectedFile().delete();
					setDirectionary(getDirectory());
				}
			}
		}

		/**
		 * paintBorder(Graphics g);
		 */
		@Override
		protected void paintBorder(Graphics g) {
			int W = getWidth();
			int H = getHeight();
			Graphics2D g2d 	= (Graphics2D) g.create();
			g2d.setColor(COLOR1);
			g2d.drawRect(0, 0, W - 1, H - 1);
			g2d.dispose();
		}
	}
	
	/**
	 * setValueAt(Object aValue, int row, int column);
	 */
	@Override
    public void setValueAt(Object aValue, int row, int column) {
		System.out.println(aValue);
		System.out.println(row);
		System.out.println(column);
        getModel().setValueAt(aValue, convertRowIndexToModel(row),
                              convertColumnIndexToModel(column));
    }
	
	@Override
	public boolean editCellAt(int row, int column, EventObject e){
		if (editable == false) {
			return false;
		}
		return super.editCellAt(row, column, e);
	}
}
